using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using DG.Tweening;
using AppEventUtils;
using System;
using AppGameState;
using Unity.VisualScripting;
using UnityEngine.EventSystems;


public class DragCard : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler, IPointerClickHandler, IPointerDownHandler, IPointerUpHandler, IPointerEnterHandler, IPointerExitHandler
{
    private float requiredTime = 0.5f; // 悬停所需时间（秒）

    private bool isHovering = false; // 是否正在悬停
    private float hoverTime = 0f;    // 悬停计时器
    
    public Transform parent;
    
    Vector3 origin_position;
    Vector3 parent_origin_position;
    Vector3 begin_position;
    Vector3 end_position;

    [HideInInspector] public CardController card_comp;

    // [HideInInspector]
    // public CardController card_comp
    // {
    //     get
    //     {
    //         return parent.gameObject.GetComponent<CardController>();
    //     }
    // }

    // public void update_card_comp(CardController card_comp)
    // {
    //     // card_comp = parent.gameObject.GetComponent<CardController>();
    //     this.card_comp = card_comp;
    // }
    
    public void update_card_comp()
    {
        card_comp = parent.gameObject.GetComponent<CardController>();
        // this.card_comp = card_comp;
    }

    private bool has_remove_from_ls;

    private bool force_end_drag = false;
    private bool is_dragging = false;
    
    public bool is_activated
    {
        get
        {
            if (GameStateManager.instance == null)
                return true;
            return GameStateManager.instance.get_current_state() == GameStateEnum.Store.ToString();
            // return true;
            // return false;
        }
    }

    private void Start()
    {
        card_comp = parent.GetComponent<CardController>();
        BdPackage.BdUtils.assert(card_comp);
        // BdPackage.BdUtils.assert(parent.GetComponent<CardController>());
    }

    private void OnHoverComplete()
    {
        // Debug.Log("用户悬停 1 秒，触发逻辑！");
        // 在这里实现你的业务逻辑，例如显示卡牌详细信息
        card_comp.btn_show_card_info_ui(true);
    }

    public void OnPointerEnter(PointerEventData eventData)
    {
        isHovering = true; // 鼠标进入目标
        hoverTime = 0f;    // 重置计时器
        
        card_comp.change_to_remind_player__big();
    }

    public void OnPointerExit(PointerEventData eventData)
    {
        isHovering = false; // 鼠标离开目标
        hoverTime = 0f;     // 重置计时器

        card_comp.change_to_remind_player__original();
        card_comp.btn_show_card_info_ui(false);
    }

    public void OnPointerDown(PointerEventData eventData)
    {
        isHovering = true; // 开始计时（触屏或鼠标按下）
        hoverTime = 0f;    // 重置计时器
    }

    public void OnPointerUp(PointerEventData eventData)
    {
        isHovering = false; // 停止计时（触屏或鼠标松开）
        hoverTime = 0f;     // 重置计时器
    }

    private bool is_waiting_select_state => GameController.instance.is_waiting_select_state;
    public void OnPointerClick(PointerEventData eventData)
    {
        // BdPackage.BdUtils.log($"=== OnPointerClick, card_comp's obj_name: {card_comp.gameObject.name}, card_name: {card_comp.card_data.card_name}, {card_comp.card_data}");

        if (eventData.button == PointerEventData.InputButton.Right)
        {
            BdPackage.BdUtils.log("shield 鼠标右键被点击了！", card_comp.shield_animator.gameObject.activeInHierarchy, card_comp.card_data.card_name);
            // card_comp.shield_animator.gameObject.SetActive(false);
            
            var buff_comp = card_comp.gameObject.GetComponent<BuffHandle>();
            // buff_comp.FindBuff(GameController.instance.get_buff_id(card_comp.card_data.id)) == null;
            buff_comp.show_all_buff_listeners();
        }
        
        if (is_waiting_select_state)
        {
            BdPackage.BdUtils.log($"=== OnPointerClick, need_select_num: {GameController.instance.need_select_num}");

            // int exclude_i = card_comp.parameter.ordering;
            var target_role = card_comp.parameter.belong_to;
            
            if (GameController.instance.selected_cards.Contains(card_comp))
            {
                // 重复选中就是取消
                card_comp.select_effect.SetActive(false);
                GameController.instance.selected_cards.Remove(card_comp);
                GameController.instance.need_select_num += 1;
            }
            else
            {
                // --- 这里把选中信息处理下
                card_comp.select_effect.SetActive(true);
                GameController.instance.selected_cards.Add(card_comp);
                GameController.instance.need_select_num -= 1;
            }
            
            // if (GameController.instance.need_select_num <= 0)
            // {
            //     GameController.instance.change_soldiers_to_waiting_select_state(target_i: -1, target_role: target_role, big_flag: false);
            // }
            // else
            // {
            //     // 这里应该显示一点特效, 表明正处于[选中状态]. 并且得处理下重复选中的问题.
            // }
        }
    }
    public void OnBeginDrag(PointerEventData eventData) 
    {
        if (!is_activated)
            return;

        if (is_waiting_select_state)
            return;

        card_comp.change_to_remind_player__big(top: true);
        
        is_dragging = true;
        
        begin_position = eventData.position;
        origin_position = eventData.position;
        parent_origin_position = parent.position;

        // BdPackage.BdUtils.log("=== OnBeginDrag, screen origin_position:", origin_position, "word origin_position", conv_screen_pos_to_world_pos(origin_position));
        // parent.position = new Vector3(parent.position.x, parent.position.y, -1f);
        has_remove_from_ls = false;
        force_end_drag = false;
    }
    
    public void OnDrag(PointerEventData eventData)
    {
        if (!is_dragging)
            return;
        
        if (!is_activated)
        {
            // if (has_remove_from_ls)
            call_end_drag(is_cancel: true);
            force_end_drag = true;
            return;
        }
        // BdPackage.BdUtils.log("=== OnDrag");
        end_position = eventData.position;
        move_to_end_position();
    }

    public Vector3 conv_screen_pos_to_world_pos(Vector3 screen_pos)
    {
        Vector3 word_pos = Camera.main.ScreenToWorldPoint(new Vector3(screen_pos.x, screen_pos.y, Camera.main.nearClipPlane));

        return word_pos;
        // return Camera.main.ScreenToWorldPoint(screen_pos);
    }

    private float center_of_place_y => ScreenPlaceManager.instance.center_of_soldier_place.y;
    private RectBounds rect_bounds => ScreenPlaceManager.instance.rect_bounds;
    
    CardParameter card_parameter => card_comp.parameter;
    CardData card_data => card_comp.parameter.card_data;

    public void call_end_drag(bool is_cancel = false)
    {
        is_dragging = false;

        card_comp.change_to_remind_player__original();
        
        if (is_cancel)
        {
            BdPackage.BdUtils.log($"--- 发起[取消拖拽]事件, belong_to: {card_comp.parameter.belong_to}");
            
            if (has_remove_from_ls)
                GameController.instance.move_card_to_selected_place(card_comp);
            else
                parent.DOMove(parent_origin_position, 0.2f);
            return;
        }
            
        parent.position = new Vector3(parent.position.x, parent.position.y, 0f);

        origin_position = end_position;
        
        var old_ordering = card_parameter.ordering;
        var old_is_in_hand = card_parameter.is_in_hand;
        var old_belong_to = card_parameter.belong_to;

        // var word_position__end = ScreenPositionTools.conv_screen_pos_to_word_pos(end_position);
        var word_position__end = parent.position;

        // ScreenPlaceManager
        if (has_remove_from_ls && card_comp.parameter.belong_to != RoleTypeEnum.None)  // 移动成功
        {
            // 位置不对, 则返回去
            bool flag_error_place = true;
            Vector3 mouse_pos = ScreenPositionTools.conv_screen_pos_to_word_pos(Input.mousePosition);
            Vector3 current_obj_pos = parent.position;
            RoleTypeEnum target_role = RoleTypeEnum.None;
            bool is_in_hand = false;

            RoleTypeEnum select_target_role = RoleTypeEnum.None;
            int select_num = 0;

            if (card_comp.parameter.belong_to == RoleTypeEnum.store_owner)
            {
                if (word_position__end.y < rect_bounds.middle_place.down)  // 小于中心点, 则发起购买事件
                {
                    BdPackage.BdUtils.log($"----- 发起[购买]事件, word_position__end.y: {word_position__end.y}, rect_bounds.middle_place.down: {rect_bounds.middle_place.down}");
                    target_role = RoleTypeEnum.player;
                    is_in_hand = true;
                    mouse_pos = new Vector3(100f, 0);
                }
                else if (word_position__end.y <= rect_bounds.soldier_place_top.top + 0.5f)  // 大于顶部点, 则发起出售事件
                {
                    BdPackage.BdUtils.log("----- 发起[交换酒馆随从位置]事件");
                    target_role = RoleTypeEnum.store_owner;
                }
            }
            else if (card_comp.parameter.belong_to == RoleTypeEnum.player)
            {
                if (card_comp.parameter.is_in_hand)
                {
                    if (word_position__end.y > rect_bounds.player_hands_place.top) // 大于`soldier_place_down`的中心区域, 则发起[使用卡牌]事件
                    {
                        BdPackage.BdUtils.log("----- 发起[使用卡牌]事件");
                        target_role = RoleTypeEnum.player;

                        var use_target_num = card_data.use_target_num;
                        if (use_target_num > 0)
                        {
                            select_num = use_target_num;
                            select_target_role = target_role;
                        }
                    }
                    else
                    {
                        BdPackage.BdUtils.log("----- 发起[使用卡牌]事件失败, 返回手牌!");
                        target_role = RoleTypeEnum.player;
                        is_in_hand = true;
                    }
                }
                else
                {
                    if (word_position__end.y > rect_bounds.middle_place.top)  // 大于中心区域,则发起[卖出]事件
                    {
                        BdPackage.BdUtils.log("----- 发起[返回酒馆]事件, 后面应修改为[卖出]事件");
                        target_role = RoleTypeEnum.store_owner;
                    }
                    else
                    {
                        BdPackage.BdUtils.log("----- 发起[交换player随从位置]事件");
                        target_role = RoleTypeEnum.player;
                    }
                }
            }
            
            if (target_role != RoleTypeEnum.None)
            {
                if (target_role == RoleTypeEnum.store_owner && old_belong_to == RoleTypeEnum.player)
                {
                    BdPackage.BdUtils.log("----- 发起[卖出]事件");
                    BaseInfoManager.instance.sale_soldier();
                    flag_error_place = false;

                    card_comp.show_sale_effect_animation();
                    // card_comp.sale_effect.SetActive(false);
                    // card_comp.sale_effect.SetActive(true);
                    // GameController.instance.recycle_one_card(card_comp);
                }
                else
                {
                    var success_flag = GameController.instance.move_card_to_selected_place(current_obj_pos, card_comp, target_role: target_role, is_in_hand: is_in_hand);
                    if (success_flag)
                    {
                        flag_error_place = false;

                        if (target_role == RoleTypeEnum.player && !is_in_hand && old_is_in_hand)
                        {
                        
                            var card_ls = GameController.instance.role_cards_dc[target_role][is_in_hand];
                    
                            if (select_num > 0 && card_ls.Count != 1)
                            {
                                BdPackage.BdUtils.log($"--- 需要选择[{select_num}]张[{select_target_role}]的牌!");
                    
                                bool need_confirm = select_num >= 2;
                                StartCoroutine(GameController.instance.start_select_event(
                                    card_comp, select_num, select_target_role, old_belong_to, old_is_in_hand, old_ordering, need_confirm));
                            }
                            else
                            {
                                card_comp.create_sale_effect(z: 0f, force_wait_time: 0.1f);

                                card_comp.OnUse();

                                string msg = "发起[使用卡牌]事件";
                                EventManager.instance.FireEvent(CardEventTypeEnum.OnUse.ToString(), msg);
                            }
                        }
                    }
                }
            }
            
            if (flag_error_place)
            {
                BdPackage.BdUtils.log($"*** flag_error_place 使用卡牌失败! target_role: {target_role}");
                GameController.instance.move_card_to_selected_place(card_comp);
            }
        }
        else
        {
            parent.DOMove(parent_origin_position, 0.2f);
        }
    }

    void IEndDragHandler.OnEndDrag(PointerEventData eventData)
    {
        if (force_end_drag || !is_dragging)
            return;
        
        if (!is_activated)
        {
            call_end_drag(is_cancel: true);
            return;
        }

        // BdPackage.BdUtils.log("=== OnEndDrag");
        end_position = eventData.position;
        
        move_to_end_position();
        
        call_end_drag();
    }

    public Vector3 get_delta_for_2_pos(Vector3 screen_pos_1, Vector3 screen_pos_2, bool is_screen_pos_or_word_pos = false) => 
        ScreenPositionTools.get_delta_for_2_pos(screen_pos_1, screen_pos_2, is_screen_pos_or_word_pos);
    
    public void move_to_end_position(bool is_screen_pos_or_word_pos = false)
    {
        var delta = get_delta_for_2_pos(begin_position, end_position, is_screen_pos_or_word_pos);
        if (delta.magnitude > 0.01f)
        {
            // transform.position += delta;
            begin_position = end_position;

            // parent.transform.position = is_screen_pos_or_word_pos? transform.position: Camera.main.ScreenToWorldPoint(new Vector3(transform.position.x, transform.position.y, Camera.main.nearClipPlane));
            parent.transform.position += delta;
        }
        
        var total_delta = get_delta_for_2_pos(origin_position, end_position, is_screen_pos_or_word_pos);
        if (total_delta.magnitude > 1f && !has_remove_from_ls)
        {
            has_remove_from_ls = true;
            GameController.instance.remove_card_from_selected_place(card_comp, recycle_card: false);
        }
    }

    // private BdPackage.BdTools.TimeIntervalUtil timer = new BdPackage.BdTools.TimeIntervalUtil(interval: 0.1f);
    private float last_time = 0f;
    
    private void Update()
    {
        if (!is_dragging)
        {
            if (isHovering)
            {
                hoverTime += Time.deltaTime; // 累计悬停时间

                if (hoverTime >= requiredTime)
                {
                    OnHoverComplete(); // 触发悬停完成逻辑
                    isHovering = false; // 防止多次触发
                }
            }
        }
        
        if (Time.time - last_time > 0.1f)
        {
            if (is_dragging && !is_activated)
            {
                call_end_drag(is_cancel: true);            
            }
            last_time = Time.time;
        }
        
        if (!is_activated)
            return;

        if (is_dragging)
        {
            if (card_comp.card_ui_obj.activeInHierarchy)
                card_comp.btn_show_card_info_ui(false);
        }
        // if (timer.is_time_to_run())
    }
}
